/**
 * 
 */
package com.ruyipu.forum.activity;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.ruyipu.forum.R;
import com.ruyipu.forum.adapter.CategoryAdapter;
import com.ruyipu.forum.base.GlobalUtil;
import com.ruyipu.forum.base.Header;
import com.ruyipu.forum.base.MyLog;
import com.ruyipu.forum.interfaces.IItem;
import com.ruyipu.forum.item.Category;
import com.ruyipu.forum.model.CategoryModel;

/**
 * @author donald
 * 
 */
public class AllCategories extends BaseActivity {

	public static final String TAG = AllCategories.class.getSimpleName();
	public static final String NAME = AllCategories.class.getName();

	private List<IItem> dataList = new ArrayList<IItem>();
	private CategoryAdapter myAdapter;
	private ListView lvCategory;

	protected void onCreate(Bundle savedInstanceState) {

		setContentView(R.layout.allcategories);

		super.onCreate(savedInstanceState);

		refresh(null);
	}

	@Override
	protected void makeWidget() {
		myHeader = new Header(this, "Category List");

		lvCategory = (ListView) findViewById(R.id.lvCategoryList);
	}

	@Override
	protected void initWidget() {
		lvCategory.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				viewCategory((Category) dataList.get(arg2));
			}
		});
	}

	private void viewCategory(Category category) {
		Intent intent = new Intent();
		intent.putExtra(Category.TAG, category);
		intent.setClassName(this, CategoryActivity.NAME);
		GlobalUtil.startSonActivity(this, intent);
	}

	@Override
	public void refresh(View v) {
		super.refresh(v);
		new MyDownloader().execute("");
	}

	private class MyDownloader extends AsyncDownloader {

		@Override
		protected JSONObject doInBackground(Object... params) {
			return CategoryModel.getInstance().getAllCategory(
					AllCategories.this);
		}
	}

	@Override
	protected void updateData(JSONObject jsonObject) {
		if (null == jsonObject) {
			return;
		}
		List<IItem> tempList = CategoryModel.getInstance().getCategoriesFrom(
				jsonObject);
		if (!tempList.isEmpty()) {
			if (dataList.isEmpty()) {
				dataList.addAll(tempList);
				myAdapter = new CategoryAdapter(AllCategories.this, dataList);
				lvCategory.setAdapter(myAdapter);
				lvCategory.setLayoutAnimation(lacList);
			} else {
				// TODO update data list
				MyLog.w(TAG, "TODO update dataList");
				myAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	protected void loadLocalData() {
		JSONObject jsonObject = CategoryModel.getInstance()
				.loadLocalAllCategory();
		updateData(jsonObject);
	}

}